import router from './routers'
import {useUserStore} from "@/store/modules/user";
import {getToken} from "@/utils/auth";

const whiteList = ['/login']


router.beforeEach((to, from, next) => {
    const store = useUserStore()
    if (getToken()) {
        //已登录且要跳转的页面是登录页
        if (to.path === '/login') {
            next({path: '/'})
        } else {
            //判断用户是否已经拉取完userInfo信息
            if (store.getRoles.length === 0) {
                store.GetInfo().then(() => {
                    next()
                }).catch(() => {
                    store.LogOut().then(() => {
                        //为了重新实例化vue-router对象，避免bug
                        location.reload()
                    })
                })
            } else {
                next()
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            //在免登录白名单，直接进入
            next()
        } else {
            //否则重定向到登录页
            next(`/login?redirect=${to.fullPath}`)
        }
    }
})